package com.yra.controller.mall;

import com.yra.domain.Category;
import com.yra.service.CategoryService;
import com.yra.service.ProductService;
import com.yra.util.PageQueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author: yrq
 * @Date: Create in 9:16 2019/12/6
 */
@Controller
@RequestMapping
public class SearchMallController {
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;

    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public ModelAndView goToSerach(@RequestParam Map<String,Object> params, HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mall/search");
        if (StringUtils.isEmpty(params.get("page"))) {
            params.put("page", 1);
        }
        params.put("limit", 10);

        if (params.containsKey("productCategoryId") && !StringUtils.isEmpty(params.get("productCategoryId") + "")) {
            int categoryId = Integer.valueOf(params.get("productCategoryId") + "");
            Category category = categoryService.categoryListByCategoryId(categoryId);
            Category categoryParent = categoryService.categoryListByCategoryId(category.getParentId());
            List<Category> categories = categoryService.categoryListByLevelAndParentId(category.getCategoryLevel(), category.getParentId());
            if (category != null) {
                request.setAttribute("productCategoryId", categoryId);
                request.setAttribute("categories", categories);
                request.setAttribute("categoryName",category.getCategoryName());
                request.setAttribute("categoryParentName",categoryParent.getCategoryName());
            }
        }

        String keyword = "";
        //对keyword做过滤 去掉空格
        if (params.containsKey("keyword") && !StringUtils.isEmpty((params.get("keyword") + "").trim())) {
            keyword = params.get("keyword") + "";
        }
        request.setAttribute("keyword", keyword);
        params.put("keyword", keyword);
        PageQueryUtil pageQueryUtil = new PageQueryUtil(params);
        productService.queryProductList(pageQueryUtil);
        request.setAttribute("pageResult", productService.queryProductList(pageQueryUtil));
        return mv;
    }
}
